package cn.smart.epic.core.aop;

import cn.smart.epic.common.constant.tips.ErrorTip;
import cn.smart.epic.common.exception.BussinessException;
import cn.smart.epic.common.exception.InvalidKaptchaException;
import cn.smart.epic.core.support.HttpKit;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @Auther Uncle_Z
 * @date 2017/9/23 23:31
 * @Email:2545375@qq.com
 * @Descrition 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * @since 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     *
     * 业务异常
     *
     * @param
     * @return
     * @Auther Z.B
     * @date 2017/9/25 22:30
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorTip notFount(BussinessException e){
        HttpKit.getRequest().setAttribute("tip",e.getMessage());
        logger.error("业务异常",e);
        return new ErrorTip(e.getCode(),e.getMessage());
    }

    /**
     *
     * 用户未登陆
     *
     * @param
     * @return
     * @Auther Z.B
     * @date 2017/9/25 22:30
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String unAuth(AuthenticationException e){
        logger.error("用户未登陆");
        return "用户未登陆";
    }

    /**
     *
     * 帐号被冻结
     *
     * @param
     * @return
     * @Auther Z.B
     * @date 2017/9/25 22:29
     */
    @ExceptionHandler(DisabledAccountException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String accountLocked(DisabledAccountException e){
        logger.error("帐号被冻结");
        return "帐号被冻结";
    }

    /**
     *
     *账号密码错误
     *
     * @param
     * @return
     * @Auther Z.B
     * @date 2017/9/25 22:29
     */
    @ExceptionHandler(CredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String credentials(CredentialsException e){
        logger.error("帐号密码错误",e);
        return "帐号密码错误";
    }

    /**
     *
     *验证码错误
     *
     * @param
     * @return
     * @Auther Z.B
     * @date 2017/9/25 22:29
     */
    @ExceptionHandler(InvalidKaptchaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String credentials(InvalidKaptchaException e){
        logger.error("验证码错误",e);
        return "验证码错误";
    }
}
